﻿
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[F_Split]'))
DROP FUNCTION [F_Split]
GO
CREATE FUNCTION [F_Split](@List NVARCHAR(MAX),@Spliter NVARCHAR(1024))
RETURNS @Tab TABLE([_Index] INT PRIMARY KEY IDENTITY(1,1),[_Item] NVARCHAR(MAX))
AS
BEGIN
	--<Summary>分割字符串</Summary>	
	DECLARE @Index INT,@LastIndex INT,@MaxLen INT,@Current NVARCHAR(MAX),@Len INT;
	SET @MaxLen=LEN(@List);
	IF(@List IS NULL OR @MaxLen <1)RETURN ;
	IF(@Spliter IS NULL )SET @Spliter=',';
	SET @Index=1 ;
	SET @LastIndex=1;

	SET @Len=LEN(@Spliter);
	WHILE (@Index<=@MaxLen AND @Index!=0)
	BEGIN
		SET @Index=CHARINDEX(@Spliter,@List,@LastIndex);
		IF (@Index=0)
		BEGIN
			SET @Current=SUBSTRING(@List, @LastIndex,@MaxLen-@LastIndex+1);
		END
		ELSE
		BEGIN			
			SET @Current=SUBSTRING(@List,@LastIndex,@Index-@LastIndex);
		END
		SET @LastIndex=@Index+@Len;
		INSERT INTO @Tab ( _Item )
		VALUES  ( @Current );
	END
   	RETURN
END
GO